import axios, { AxiosRequestConfig } from "axios";
import { baseURL } from "../constant/url";
import { getLocalJWT } from "./authApi";

axios.defaults.baseURL = baseURL;

axios.interceptors.request.use((config: AxiosRequestConfig) => {
  if (typeof window !== "undefined") {
    config.headers.Authorization = getLocalJWT();
  }
  return config;
});

export default axios;
export const { get, post } = axios;

export const query: (
  url: string,
  config?: AxiosRequestConfig | undefined
) => Promise<any> = async (url, config) =>
  await get(url, config)
    .then(res => res)
    // .then(res => res.data)
    .catch(err => {
      console.error(url + " err", err, err.response);
      const message = err.response?.data?.message;
      if (message) console.log({ message });
      return { err: err.response };
    });

export const request: <T = any>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig | undefined
) => Promise<{ data?: T; err?: Response }> = (...props) => {
  return new Promise(resolve => {
    post(...props)
      .then(res => resolve(res))
      .catch(err => {
        // reject(err); // 配合await 使用catch时会遇到debug 😡
        console.error("request" + props[0] + " err", err, err.response);
        const message = err.response?.data?.message;
        if (message) console.log({ message });
        resolve({ err: err.response });
      });
  });
};
